package com.agileai.portal.portlets.tagcloud;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;

import org.dom4j.Document;
import org.dom4j.Element;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.portal.bizmoduler.wcm.KeyWordsTreeManage;
import com.agileai.portal.driver.GenericPotboyPortlet;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.portlets.PortletCacheModel;
import com.agileai.util.StringUtil;
import com.agileai.util.XmlUtil;

public class TagCloudPortlet extends GenericPotboyPortlet {
	private static HashMap<String,PortletCacheModel> ModelCache = new HashMap<String,PortletCacheModel>();
	@RenderMode(name = "view")
	public void view(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences =  PreferencesHelper.getPublicPreference(request);
		String height = preferences.getValue("height", null);
		String width = preferences.getValue("width", null);
		String targetPageURL = preferences.getValue("targetPageURL", null);

		if (!StringUtil.isNullOrEmpty(height) 
				&& !StringUtil.isNullOrEmpty(width) && !StringUtil.isNullOrEmpty(targetPageURL)){
			request.setAttribute("isSetting", "Y");
		}else{
			request.setAttribute("isSetting", "N");
		}
		
		String isSetting = (String)request.getAttribute("isSetting");
		if ("Y".equals(isSetting)){
			request.setAttribute("height", height);
			request.setAttribute("width", width);
		}
		super.doView(request, response);
	}
	@RenderMode(name = "edit")
	public void edit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String height = preferences.getValue("height", "250");
		String width = preferences.getValue("width", "247");
		String targetPageURL = preferences.getValue("targetPageURL", null);
		String defaultVariableValues = preferences.getValue("defaultVariableValues", null);
		String isCache = preferences.getValue("isCache", defaultIsCache);
		String cacheMinutes = preferences.getValue("cacheMinutes", defaultCacheMinutes);
		
		request.setAttribute("height", height);
		request.setAttribute("width", width);
		request.setAttribute("targetPageURL", targetPageURL);
		request.setAttribute("defaultVariableValues", defaultVariableValues);
		request.setAttribute("isCache", isCache);
		request.setAttribute("cacheMinutes", cacheMinutes);
		
		super.doEdit(request, response);
	}

	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException,
			IOException, PreferenceException {
		String height = request.getParameter("height");
		String width = request.getParameter("width");
		String targetPageURL = request.getParameter("targetPageURL");
		String defaultVariableValues = request.getParameter("defaultVariableValues");
		String isCache = request.getParameter("isCache");
		String cacheMinutes = request.getParameter("cacheMinutes");
		
		PreferencesWrapper preferWapper = new PreferencesWrapper();		
		preferWapper.setValue("height", height);
		preferWapper.setValue("width", width);
		preferWapper.setValue("targetPageURL", targetPageURL);
		preferWapper.setValue("defaultVariableValues", defaultVariableValues);
		preferWapper.setValue("isCache", isCache);
		preferWapper.setValue("cacheMinutes", cacheMinutes);
		
		PreferencesHelper.savePublicPreferences(request, preferWapper.getPreferences());	
		response.setPortletMode(PortletMode.VIEW);
	}
	
	@Resource(id="getXMLData")
	public void getXMLData(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String ajaxData = getCachedData(request);
		PrintWriter writer = response.getWriter();
		writer.print(ajaxData);
		writer.close();
	}
	
	private String retrieveData(ResourceRequest request){
		String result = "";
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String targetPageURL = preferences.getValue("targetPageURL", null);
		try {
			KeyWordsTreeManage keyWordsTreeManage = this.lookupService(KeyWordsTreeManage.class);
			List<DataRow> records =  keyWordsTreeManage.findTreeRecords(new DataParam());
			if (records != null && records.size() > 0){
				targetPageURL = "/portal/request/"+targetPageURL;
				Document document = XmlUtil.createDocument();
				Element root = document.addElement("root");
				for (int i=0;i < records.size();i++){
					DataRow row = records.get(i);
					String wordPid = row.stringValue("WORD_PID");
					String wordCode = row.stringValue("WORD_CODE");
					String wordName = row.stringValue("WORD_NAME");
					if (StringUtil.isNotNullNotEmpty(wordPid)){
						Element codeItem = root.addElement("item");
						codeItem.addAttribute("type","text");
						codeItem.addAttribute("detail",wordCode);
						codeItem.addAttribute("link", targetPageURL+"?searchWord="+wordCode);
						codeItem.addAttribute("weight", "40");
						
						Element nameItem = root.addElement("item");
						nameItem.addAttribute("type","text");
						nameItem.addAttribute("detail",wordName);
						nameItem.addAttribute("link", targetPageURL+"?searchWord="+wordName);
						nameItem.addAttribute("weight", "40");
					}
				}
				result = document.asXML();
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(),e);
		}
		return result;
	}
	
	private String getCachedData(ResourceRequest request) {
		String cacheKeyId = TagCloudPortlet.class.getName();
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String cacheMinutes = (String)preferences.getValue("cacheMinutes",defaultCacheMinutes);
		String isCache = preferences.getValue("isCache", defaultIsCache);
		String result = null;
		if ("N".equals(isCache)){
			result = this.retrieveData(request);
		}else{
			if (!ModelCache.containsKey(cacheKeyId)){
				PortletCacheModel cachedXMLData = new PortletCacheModel(cacheKeyId);
				String model = this.retrieveData(request);
				cachedXMLData.setObject(model);
				cachedXMLData.setCreateDate(new Date());
				ModelCache.put(cacheKeyId, cachedXMLData);
			}
			PortletCacheModel cacheData = ModelCache.get(cacheKeyId);

			long cacheTimeRange = Integer.parseInt(cacheMinutes) * 60  * 1000;
			long currentTime = System.currentTimeMillis();
			long cacheCreateTime =  cacheData.getCreateDate().getTime();
			
			long diffTime = currentTime -cacheCreateTime;
			if (diffTime > cacheTimeRange ){
				String model = this.retrieveData(request);
				cacheData.setObject(model);
				cacheData.setCreateDate(new Date());
			}
			result = (String)cacheData.getObject();
		}
		return result;
	}
}
